package de.tum.in.eist.poll.client;

import de.tum.in.eist.poll.client.widgets.content.ContentFactory;
import de.tum.in.eist.poll.client.widgets.content.MainUIFactory;
import de.tum.in.eist.poll.client.widgets.menu.MenuFactory;
import de.tum.in.eist.poll.client.widgets.menu.StudentMenuFactory;
import de.tum.in.eist.poll.shared.User;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */

public class EIST_POLL_36 implements EntryPoint {

	private final PollServiceAsync pollService = GWT.create(PollService.class);

	private final DockLayoutPanel layoutBody = new DockLayoutPanel(Unit.PCT);
	private final VerticalPanel center = new VerticalPanel();
	private final VerticalPanel menu = new VerticalPanel();

	public static User user = null;

	@Override
	public void onModuleLoad() {
		layoutBody.addWest(menu, 10);
		layoutBody.addNorth(new Image("./images/eistpoll.jpg"), 10);
		layoutBody.add(center);

		if (user == null) {
			center.clear();
			History.newItem("login", true);
		}

		center.add(createSpecificContent().createContent("").draw());

		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
					center.clear();
					
					pollService.loginFromSession(new AsyncCallback<User>() {
						public void onFailure(Throwable error) {
							center.clear();
							center.add(new HTML(
									"<h1>EIST Poll is currently experiencing technical difficulties.<h1>\n<h2>Error details: </h2></br><pre>"
											+ error.getMessage() + "</pre>"));
						}

						public void onSuccess(User result) {
							user = result;
							
							center.add(createSpecificContent().createContent(History.getToken()).draw());
							menu.clear();
							menu.add(createUserSpecificMenu().createMenu().draw());
						}
					});
			}
		});

		RootLayoutPanel.get().add(layoutBody);
	}

	private ContentFactory createSpecificContent() {
			return new MainUIFactory();
	}

	private MenuFactory createUserSpecificMenu() {
		int userType = 3;
		if (user != null) {
			userType = user.getUserType();
		}

		if (userType == 0) {
			return new StudentMenuFactory();
		}  else {
			return null;
		}
	}
}
